package org.example.netty.test.nio.netty.chat.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.CreateGroupMessage;
import org.example.netty.test.nio.netty.chat.bean.JoinGroupMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.bean.User;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

import java.util.List;
import java.util.Set;

/**
 * @author zp
 * @version 1.0
 * @description: 处理消息CreateGroupMessage
 * @date 2023/4/6 18:29
 */
@Slf4j
public class CreateGroupMessageHandler extends SimpleChannelInboundHandler<CreateGroupMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupMessage msg) throws Exception {
        Channel channel = ctx.channel();
        String groupName = msg.getGroupName();
        GlobalContent globalContent = GlobalContent.getInstance();
        log.debug("创建群聊的消息：{}", msg);
        // 校验群名称是否重复
        if (globalContent.isExistGroupName(groupName)) {
            SystemMessage.sendFailMessage(SystemMessageType.CREATE_NAME_JOIN_GROUP_FAIL, ctx);
        } else {
            Set<String> joinGroupUserNames = msg.getJoinGroupUserNames();
            log.debug("创建群聊的用户名单：[{}]", joinGroupUserNames);
            // 所有用户的名单
            Set<String> userNames = globalContent.getUserNames();
            // 创建群聊成功
            UserSession userSession = NettyChannelUtil.getUserSession(channel);
            assert userSession != null;
            User user = userSession.getUser();
            String userName = user.getUserName();
            joinGroupUserNames.add(userName);

            // 校验加入的用户是否都有效
            for (String addUserName : joinGroupUserNames) {
                if (!userNames.contains(addUserName)) {
                    SystemMessage.sendFailMessage(SystemMessageType.CREATE_NAME_JOIN_GROUP_NAME_LIST_FAIL, ctx);
                    return;
                }
            }

            // 获取到所有需要加入群聊的用户 session
            Set<UserSession> sessions = globalContent.getSessions(joinGroupUserNames);
            globalContent.createGroup(groupName, sessions);
            ctx.channel().writeAndFlush(msg);

        }
    }
}
